//
//  ContactExampleViewController.m
//  ContactExample
//

#import "ContactExampleViewController.h"

@implementation ContactExampleViewController

- (void)createPerson {
	ABRecordRef person = ABPersonCreate();
	CFErrorRef error = NULL;
	
	// 단일 값 속성
	ABRecordSetValue(person, kABPersonFirstNameProperty, @"Steve", &error);
	ABRecordSetValue(person, kABPersonLastNameProperty, @"Jobs", &error);
	
	// 다중 값 속성 : 전화번호
	ABMultiValueRef phoneRef = ABMultiValueCreateMutable(kABMultiStringPropertyType);
	ABMultiValueAddValueAndLabel(phoneRef, @"555-123-4567", kABPersonPhoneMainLabel, NULL);
	ABMultiValueAddValueAndLabel(phoneRef, @"554-987-6543", kABPersonPhoneMobileLabel, NULL);
	ABRecordSetValue(person, kABPersonPhoneProperty, phoneRef, &error);
	CFRelease(phoneRef);
	
	// 다중 값 속성 : 주소
	ABMutableMultiValueRef addressRef = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
	NSMutableDictionary *dict = [[NSMutableDictionary alloc]
								 initWithObjectsAndKeys:@"1 Infinite Loop", kABPersonAddressStreetKey,
								 @"Cupertino", kABPersonAddressCityKey,
								 @"California", kABPersonAddressStateKey,
								 @"95014", kABPersonAddressZIPKey,
								 @"USA", kABPersonAddressCountryKey, nil];
	ABMultiValueAddValueAndLabel(addressRef, dict, kABHomeLabel, NULL);
	ABRecordSetValue(person, kABPersonAddressProperty, addressRef, &error);
	CFRelease(addressRef);
	
	ABAddressBookRef addressBook = ABAddressBookCreate();
	ABAddressBookAddRecord(addressBook, person, &error);
	ABAddressBookSave(addressBook, &error);
	
	if (error != NULL) {
		NSLog(@"error: %@", error);
	}
	
	CFRelease(person);
	CFRelease(addressBook);
}

- (void)logAddressesForPerson:(ABRecordRef)person {
	
	ABMultiValueRef addressValues = ABRecordCopyValue(person, kABPersonAddressProperty);
	NSArray *arrAddresses = [NSArray arrayWithArray:(id)ABMultiValueCopyArrayOfAllValues(addressValues)];
	
	for (NSDictionary *addr in arrAddresses) {
		NSLog(@"Street: %@", [addr objectForKey:(NSString *)kABPersonAddressStreetKey]);
		NSLog(@"City: %@", [addr objectForKey:(NSString *)kABPersonAddressCityKey]);
		NSLog(@"State: %@", [addr objectForKey:(NSString *)kABPersonAddressStateKey]);
		NSLog(@"ZIP: %@", [addr objectForKey:(NSString *)kABPersonAddressZIPKey]);
		NSLog(@"Country: %@", [addr objectForKey:(NSString *)kABPersonAddressCountryKey]);
	}
	
	CFRelease(addressValues);
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self createPerson];

	ABAddressBookRef addressBook = ABAddressBookCreate();
	CFArrayRef contacts = ABAddressBookCopyPeopleWithName(addressBook, CFSTR("Steve Jobs"));
	ABRecordRef person = [(NSArray *)contacts objectAtIndex:0];
	[self logAddressesForPerson:person];
	
	CFRelease(contacts);
	CFRelease(addressBook);
}

- (void)dealloc {
    [super dealloc];
}

@end
